<?php
namespace app\support;

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

class Oss
{
    protected $client;
    protected $bucket;

    protected string $externalDomain= "minio";

    public function __construct()
    {
        $this->bucket = config("helper.oss.minio_bucket_name"); // 默认桶名，你可以换成自己的
        $this->client = new S3Client([
            'version'     => 'latest',
            'region'      => 'us-east-1',
            'endpoint'    => 'http://minio:9000',
            'use_path_style_endpoint' => true,
            'credentials' => [
                'key'    => 'admin',
                'secret' => 'admin123456',
            ],
        ]);

        // 自动创建桶（如果不存在）
        if (!$this->client->doesBucketExist($this->bucket)) {
            $this->client->createBucket(['Bucket' => $this->bucket]);
        }
    }

    /**
     * 上传文件
     * @throws \Exception
     */
    public function upload(string $filePath, string $objectName): string
    {
        try {
            $this->client->putObject([
                'Bucket'     => $this->bucket,
                'Key'        => $objectName,
                'SourceFile' => $filePath,
            ]);
            return $this->externalDomain . "/" . $this->bucket . "/" . $objectName;
        } catch (AwsException $e) {
            throw new \Exception("上传失败: " . $e->getMessage());
        }
    }


    /**
     * 下載文件（返回可下載的外部URL）
     */
    public function download(string $objectName): string
    {
        try {
            // 臨時授權鏈接，可以用 presign URL
            $cmd = $this->client->getCommand('GetObject', [
                'Bucket' => $this->bucket,
                'Key'    => $objectName,
            ]);
            $request = $this->client->createPresignedRequest($cmd, '+10 minutes'); // 有效期 10 分鐘

            // 用戶可訪問的對外 URL（代理域名）
            return (string) $request->getUri();

            // 如果不需要簽名，直接拼接公開地址：
            // return $this->externalDomain . "/" . $this->bucket . "/" . $objectName;

        } catch (AwsException $e) {
            throw new \Exception("下载失败: " . $e->getMessage());
        }
    }

    /**
     * 刪除文件
     */
    public function delete(string $objectName): bool
    {
        try {
            $this->client->deleteObject([
                'Bucket' => $this->bucket,
                'Key'    => $objectName,
            ]);

            return true;

        } catch (AwsException $e) {
            throw new \Exception("删除失败: " . $e->getMessage());
        }
    }
}
